package com.jy.appmarket.fragment;

import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jy.app.market.idata.data.Login;
import com.jy.appmarket.AppMarketApplication;
import com.jy.appmarket.R;
import com.jy.appmarket.activity.ApkFileManagerActivity;
import com.jy.appmarket.activity.AppUpdateActivity;
import com.jy.appmarket.activity.InstalledAppManagerActivity;
import com.jy.appmarket.activity.LogoutActivity;
import com.jy.appmarket.activity.MainActivity;
import com.jy.appmarket.activity.UmengFeedbackActivity;
import com.jy.appmarket.activity.UserLoginActivity;
import com.jy.appmarket.database.AppUpdateDatabase;
import com.jy.appmarket.utils.LoginUtil;
import com.jy.appmarket.view.CircleImageView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.umeng.fb.FeedbackAgent;
import com.umeng.fb.fragment.FeedbackFragment;

/**
 * author  :   jiangwei
 * time    :   2018/05/24
 * desc    :   首页菜单-个人资料
 * virsion :   1.0.0
 */

public class HomeMenuFragment extends Fragment implements View.OnClickListener {
    public static final int REQUEST_LOGIN_CODE = 10;
    public static final int REQUEST_LOGOUT_CODE = 11;
    private RelativeLayout rlMenuInfo;
    private CircleImageView menuHeadIcon;
    private TextView tvMenuHeadName;
    private TextView tvUpdate;
    private TextView tvManage;
    private TextView tvInstall;
    private TextView tvOpinion;
    private TextView tvLoginOut;

    private int mUpdateCount = Integer.MIN_VALUE;

    private ContentObserver mContentObserver = new ContentObserver(new Handler()) {
        @Override
        public void onChange(boolean selfChange) {
            invalidateUpdateBadgeIfNeeded();
        }

        @Override
        public void onChange(boolean selfChange, Uri uri) {
            invalidateUpdateBadgeIfNeeded();
        }
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_menu, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        showUserInfo();
        invalidateUpdateBadgeIfNeeded();
        getActivity().getContentResolver()
                .registerContentObserver(AppUpdateDatabase.URI, false, mContentObserver);
    }

    private void initView() {
        rlMenuInfo = getView().findViewById(R.id.rl_menu_info);
        rlMenuInfo.setOnClickListener(this);
        menuHeadIcon = getView().findViewById(R.id.menu_head_icon);
        tvMenuHeadName = getView().findViewById(R.id.tv_menu_head_name);
        tvUpdate = getView().findViewById(R.id.tv_home_menu_update);
        tvUpdate.setOnClickListener(this);
        tvManage = getView().findViewById(R.id.tv_home_menu_manage);
        tvManage.setOnClickListener(this);
        tvInstall = getView().findViewById(R.id.tv_home_menu_install);
        tvInstall.setOnClickListener(this);
        tvOpinion = getView().findViewById(R.id.tv_home_menu_opinion);
        tvOpinion.setOnClickListener(this);
        tvLoginOut = getView().findViewById(R.id.tv_home_menu_login_out);
        tvLoginOut.setOnClickListener(this);
    }

    public void showUserInfo() {
        if(AppMarketApplication.isLogin()) {
            Login login = AppMarketApplication.getLogin();
            if (!TextUtils.isEmpty(login.getIconUrl())) {
                ImageLoader.getInstance().displayImage(login.getIconUrl(), menuHeadIcon, new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true)
                        .resetViewBeforeLoading(false).build());
            }
            if (!TextUtils.isEmpty(login.getNickName())) {
                tvMenuHeadName.setText(login.getNickName());
            } else if (!TextUtils.isEmpty(login.getPhoneNum())) {
                String phoneNum = login.getPhoneNum();
                if (phoneNum.length() > 7) {
                    tvMenuHeadName.setText(phoneNum.substring(0, 3) + "****" + phoneNum.substring(7));
                } else {
                    tvMenuHeadName.setText(phoneNum);
                }
            } else {
                tvMenuHeadName.setText("user" + login.getUserId());
            }
        } else {
            menuHeadIcon.setImageResource(R.drawable.icon_user_logout);
            tvMenuHeadName.setText(getResources().getString(R.string.click_login));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //跳转个人资料
            case R.id.rl_menu_info:
                if(AppMarketApplication.isLogin()) {
                    startActivityForResult(new Intent(getContext(), LogoutActivity.class), REQUEST_LOGIN_CODE);
                } else {
                    startActivityForResult(new Intent(getContext(), UserLoginActivity.class), REQUEST_LOGOUT_CODE);
                    getActivity().overridePendingTransition(R.anim.bottom_in, 0);
                }
                break;
            //应用更新
            case R.id.tv_home_menu_update:
                startActivity(new Intent(getContext(), AppUpdateActivity.class));
                break;
            //安装包管理
            case R.id.tv_home_menu_manage:
                startActivity(new Intent(getContext(), ApkFileManagerActivity.class));
                break;
            //已安装应用
            case R.id.tv_home_menu_install:
                startActivity(new Intent(getContext(), InstalledAppManagerActivity.class));
                break;
            //意见反馈
            case R.id.tv_home_menu_opinion:
                startUmengFeedback();
                break;
            //退出登录
            case R.id.tv_home_menu_login_out:
                logout();
                break;
            default:
                break;
        }
    }

    private void logout(){
        LoginUtil.logout(getContext());
        AppMarketApplication.setLogin(null);
        startActivityForResult(new Intent(getContext(), UserLoginActivity.class), REQUEST_LOGOUT_CODE);
        ((MainActivity)getActivity()).closeDrawer();
    }

    private void startUmengFeedback() {
        Intent intent = new Intent(getContext(), UmengFeedbackActivity.class);
        FeedbackAgent feedbackAgent = new FeedbackAgent(getContext());
        String id = feedbackAgent.getDefaultConversation().getId();
        intent.putExtra(FeedbackFragment.BUNDLE_KEY_CONVERSATION_ID, id);
        startActivity(intent);
    }

    private void invalidateUpdateBadgeIfNeeded() {
        AppUpdateDatabase db = AppUpdateDatabase.getInstance(getContext());
        db.correctAppUpdatesDatas(getContext());
        int update = db.getCount(false);
        if (update <= 0) {
            update = Integer.MIN_VALUE;
        }

        if (update != mUpdateCount) {
            mUpdateCount = update;
        }
    }

        @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(getContext());
        showUserInfo();
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(getContext());
    }

    @Override
    public void onDestroy() {
        getActivity().getContentResolver().unregisterContentObserver(mContentObserver);
        super.onDestroy();
    }
}
